shouldThrow

Verify that expr throws the templated Exception class. This succeeds if the expression throws a child class of the template parameter.

shouldThrow
(
T : Throwable = Exception
E
)
(
lazy E expr
,
in string file = __FILE__
,
in size_t line = __LINE__
)

Return Value

Type: auto

The caught throwable.

Throws

UnitTestException on failure (when expr does not throw the expected exception)

Examples

1 void funcThrows(string msg) {
2     throw new Exception(msg);
3 }
4 
5 try {
6     auto exception = funcThrows("foo bar").shouldThrow;
7     assert(exception.msg == "foo bar");
8 } catch (Exception e) {
9     assert(false, "should not have thrown anything and threw: " ~ e.msg);
10 }
1 void func() {
2 }
3 
4 try {
5     func.shouldThrow;
6     assert(false, "Should never get here");
7 } catch (Exception e)
8     assert(e.msg == "Expression did not throw");
1 void funcAsserts() {
2     assert(false, "Oh noes");
3 }
4 
5 try {
6     funcAsserts.shouldThrow;
7     assert(false, "Should never get here");
8 } catch (Exception e)
9     assert(
10             e.msg
11             == "Expression threw core.exception.AssertError instead of the expected Exception:\nOh noes");

Meta